2023/12/231879字符

脚本化 CSS

<div style="width:100px;height:100px;background-color:#f00;"></div>
var div = document.getElementsByTagName('div')[0];
div.style  // 返回 div 的所有 css 属性
div.style.width = 200 + "px";  // 间接改变 css 样式 (其改变的是行间样式)
// js 不识别 background-color 应以小驼峰式命名
div.getBoundingClientRect();  // 获取元素 位置 || 宽高
// 根据 W3C 标准保留字前要加 css,如:cssfloat
window.getComputedStyle(div,null);  // 返回显示的 css 属性(只读)老版本 IE 不兼容
                                    // 返回一个绝对值 如:10em --> 160px
window.getComputedStyle(div, "after").width;  // 第二个值可查看伪元素属性
div.currentStyle.width;  // 只读 (IE 独有属性)

封装方法 getstyle(obj, prop)

function getStyle (elem, prop) {
    if(window.getComputedStyle){
        return window.getComputedStyle(elem, null)[prop];
    }else{
        return elem.currentStyle[prop];
    }
}

方块加速度运动

<div style="width:150px;height:150px;background-color:#f00;position:absolute;left:0;top:0;"></div>
// 封装一个方法  获取 div 显示属性
function getStyle (elem, prop) {
    if (window.getComputedStyle) {
        return window.getComputedStyle(elem, null)[prop]; // 获取行间样式显示属性
    } else {
        return elem.currentStyle[prop];  // IE 专有属性 
    }
}
// 加速运动
var div = document.getElementsByTagName('div')[0];
var speed = 30;  // 设置加速度
var timer = setInterval(function () {
    div.style.left = parseInt(getStyle(div, 'left')) + speed + 'px';  // 调用 getStyle 方法并取值
    if (parseInt(div.style.left) > 500) {
        clearInterval(timer);  // 结束运动
    }
}, 10)